from common.yaml_util import read_yaml
from snake import *


class snake_parameters:
    # 从文件中构建一条蛇
    def create_snake(self, snakeinfo):
        # 左上方开始
        # 蛇对象
        snake = Snake()
        # 头节点
        head_node = Node(img_path=GameConfig.snake_head_img)
        # 尾节点
        tail_node = Node(img_path=GameConfig.snake_tail_img)
        head_point = Point(snakeinfo['head_px'], snakeinfo['head_py'])
        tail_point = Point(snakeinfo['tail_px'], snakeinfo['tail_py'])
        # 蛇的头尾部设置
        snake.set_head(node=head_node, point=head_point)
        snake.set_tail(node=tail_node, point=tail_point)
        # 蛇的方向设置
        snake.direction = snakeinfo['direction']
        # 身体的图片设置
        food_img_path = snakeinfo['food_img_path']
        # 蛇的身体构建
        if 'body_px' in snakeinfo and 'body_py' in snakeinfo:
            for px, py in zip(snakeinfo['body_px'], snakeinfo['body_py']):
                food_node = Node(food_img_path)
                food_point = Point(px, py)
                food = Food(node=food_node, point=food_point)
                snake_node = food.to_snake_node()
                snake.body.append(snake_node)
        self.create_stomach(snakeinfo, snake)
        # self.print_stomach_info(snake)
        # 判断蛇是否连续
        if self.snake_is_continuous(snake):
            return snake
        else:
            return None

    # 判断蛇是否连续
    def snake_is_continuous(self, snake):
        nodes = snake.to_list()
        node = nodes[0]
        for i in range(1, len(nodes)):
            if node.point.px == nodes[i].point.px:
                if node.point.py == nodes[i].point.py + 1 or node.point.py == nodes[i].point.py - 1:
                    node = nodes[i]
                    continue
                else:
                    return False
            elif node.point.py == nodes[i].point.py:
                if node.point.px == nodes[i].point.px + 1 or node.point.px == nodes[i].point.px - 1:
                    node = nodes[i]
                    continue
                else:
                    return False
            else:
                return False
        return True

    # 创建蛇的胃部
    def create_stomach(self, snakeinfo, snake):
        if 'food_px' in snakeinfo and 'food_py' in snakeinfo and snakeinfo['food_px'] is not None\
                and snakeinfo['food_py'] is not None:
            # 构建食物节点
            food_node = Node(snakeinfo['food_img_path'])
            for px, py in zip(snakeinfo['food_px'], snakeinfo['food_py']):
                food_point = Point(px, py)
                food = Food(node=food_node, point=food_point)
                if GameJudge.is_collide_food(snake.head, food):
                    snake.stomach.append(food)
        else:
            return None

    # 打印胃部信息
    def print_stomach_info(self, snake):
        for food in snake.stomach:
            print(food.point.px, food.point.py)
